#pragma once

#include <memory>
#include <atomic>
#include <arpa/inet.h>

#include <sys/uio.h>

#include "Buffer.h"
#include "HTTPRequest.h"
#include "HTTPResponse.h"

class HTTPConnection {
private:
    int client_fd{};
    struct sockaddr_in client_address{};
    bool is_close{};
    bool is_keep_alive;
    int iov_count;
    std::vector<struct iovec> iov;
//    struct iovec iov[2];
    Buffer read_buffer;
    Buffer write_buffer;

    std::unique_ptr<HTTPRequest> request;
    std::unique_ptr<HTTPResponse> response;

public:
    HTTPConnection();

    HTTPConnection(int fd, const struct sockaddr_in &client);

    ~HTTPConnection();

    HTTPConnection(HTTPConnection &&other) noexcept;

    void init_connection(int fd, const struct sockaddr_in &client);

    // 对外暴露获取客户端连接的接口
    int get_client_fd() const;

    struct sockaddr_in get_client_address() const;    // TODO: 返回一个结构体？应该能优化，用移动语义？
    std::string get_client_ip() const;

    uint16_t get_client_port() const;

    bool read(int &error);    // 没有写设置模式LT还是ET。默认以ET模式，所以要循环一次性读完
    bool write(int &error);   // 处理写事件

    void set_writer_buffer(const char *string);

    bool get_is_keep_alive() const;

    void parse_connection();  // 解析连接属性

    static std::string directory;               // 标记资源目录
//    static std::atomic<int> connections_count;  // 用户连接总数

};